#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>

#include "../include/display_goods.h"
#include "../include/unicom.h"

/*
 *写货物信息到数据库
 **/
#define WEB_GOODS_ST1_SQLITE "/warehouse.db"
#define GOODS_ID_NUM 8

// int goods_id_num = 0;

int callback(void *para, int n_column, char **column_value, char **column_name)
{
	struct _goods_info *goods_info = (struct _goods_info *)para;
	goods_info->storage_no = (int)atoi(column_value[0]);
	goods_info->goods_id = (int)atoi(column_value[1]);
	goods_info->goods_count = (int)atoi(column_value[2]);
	strcpy(goods_info->goods_time, column_value[3]);

	return 0;
}

int write_rfid2sql(struct sendGoods *p_goods_info)
{
	sqlite3 *db = NULL;
	char *err_msg = NULL;
	int ret = 0;
	char sql[1024] = {0};
	struct _goods_info goods_info_res;

	/*根据rfid信息查询数据库
	 **/
	sprintf(sql, "select * from goods where dev_no = '%d' and goodsId = '%d';",
			p_goods_info->snum, p_goods_info->goodsno);

	ret = sqlite3_open(WEB_GOODS_ST1_SQLITE, &db);
	if (ret != SQLITE_OK)
	{
		fprintf(stderr, "sqlite3_open:%s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return -1;
	}
	else
	{
		memset(&goods_info_res, 0, sizeof(struct _goods_info));
		ret = sqlite3_exec(db, sql, callback, &goods_info_res, &err_msg);
		if (ret != SQLITE_OK)
		{
			fprintf(stderr, "sqlite3_exec select:%s\n", sqlite3_errmsg(db));
			sqlite3_close(db);
			return -1;
		}

		/*
		 *如果无查询结果，回调函数调用次数为零，结构体保持清零状态
		 **/
		if (goods_info_res.storage_no == 0)
		{
			fprintf(stderr, "Warning: Have no result with this select statement!\n");
			sqlite3_close(db);
			return -1;
		}
		else
		{
			int comp_flag = 0;
			if (p_goods_info->io == 79)
			{
				comp_flag = -1;
			}
			else if (p_goods_info->io == 73)
			{
				comp_flag = 1;
			}
			goods_info_res.goods_count = goods_info_res.goods_count +
										 comp_flag * p_goods_info->goodsnum;

			if (goods_info_res.goods_count >= 0)
			{
				sprintf(sql, "update goods set goodsCount=%d where dev_no = '%d' and goodsId = '%d';",
						goods_info_res.goods_count, p_goods_info->snum, p_goods_info->goodsno);
				ret = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
				if (ret != SQLITE_OK)
				{
					fprintf(stderr, "sqlite3_exec update:%s\n", sqlite3_errmsg(db));
					sqlite3_close(db);
					return -1;
				}
			}
			else
			{
				fprintf(stderr, "goods num is wrong, didn't update sql\n");
				sqlite3_close(db);
				return -1;
			}
		}
	}
	sqlite3_close(db);
	return 0;
}
